package com.itcms.core.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.itcms.core.domain.Info;
import com.itcms.core.domain.InfoNode;
import com.itcms.core.domain.NodeExt;
import com.itcms.core.domain.InfoNode.InfoNodeId;
import com.itcms.core.domain.Node;
import com.itcms.core.repository.InfoNodeDao;
import com.itcms.core.service.InfoNodeService;
import com.itcms.core.service.NodeQueryService;

@Service
@Transactional(readOnly = true)
public class InfoNodeServiceImpl implements InfoNodeService {
	private InfoNode findOrCreate(Info info, Node node) {
		InfoNode bean = dao.findOne(new InfoNodeId(info.getId(), node.getId()));
		if (bean == null) {
			bean = new InfoNode(info, node);
		}
		return bean;
	}

	@Transactional
	public List<InfoNode> update(Info info, Integer[] nodeIds, Integer nodeId) {
		// 主栏目为null，不更新。
		if (nodeId == null) {
			return null;
		}
		if (nodeIds == null) {
			nodeIds = new Integer[0];
			
		} else {
			nodeIds = ArrayUtils.removeElement(nodeIds, nodeId);
		}
		
		//新增时，nodeIds为空，需要从扩展栏目中获取关联栏目id，并放到nodeIds中
		if(StringUtils.isEmpty(nodeIds) || nodeIds.length==0){
			List<Integer> nodeExtIds = new ArrayList<>();
			List<NodeExt> nodeExts = info.getNode().getNodeExts();
			for (NodeExt nodeExt : nodeExts) {
				nodeExtIds.add(nodeExt.getNodeExt().getId());
			}
			nodeIds = nodeExtIds.toArray(new Integer[0]);
		}
		//new:从nodeIds中去除扩展栏目id
		 /*List<NodeExt> nodeExts = info.getNode().getNodeExts();
		for (NodeExt nodeExt : nodeExts) {
			//nodeIds为空，说明为新增吗，需要先获取扩展nodeExts
			if(StringUtils.isEmpty(nodeIds) || nodeIds.length==0){
				nodeExtIds.add(nodeExt.getNodeExt().getId());
			}else{
				nodeIds = ArrayUtils.removeElement(nodeIds, nodeExt.getNodeExt().getId());
			}
		}
		if(StringUtils.isEmpty(nodeIds) || nodeIds.length==0){
			nodeIds = nodeExtIds.toArray(new Integer[0]);
		}*/
		
		List<InfoNode> infoNodes = info.getInfoNodes();
		infoNodes.clear();
		infoNodes.add(findOrCreate(info, nodeService.get(nodeId)));
		for (Integer id : nodeIds) {
			infoNodes.add(findOrCreate(info, nodeService.get(id)));
		}
		return infoNodes;
	}

	@Transactional
	public int moveByNodeId(Collection<Integer> nodeIds, Integer nodeId) {
		return dao.moveByNodeId(nodeIds, nodeId);
	}

	@Override
	@Transactional
	public int deleteByNodeId(Integer nodeId) {
		return dao.deleteByNodeId(nodeId);
	}

	private NodeQueryService nodeService;

	@Autowired
	public void setNodeQueryService(NodeQueryService nodeService) {
		this.nodeService = nodeService;
	}

	private InfoNodeDao dao;

	@Autowired
	public void setDao(InfoNodeDao dao) {
		this.dao = dao;
	}
}
